package top.anka1.fxgui;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;

import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import top.anka1.ims.*;
import top.anka1.ims.RestaurantManagementSystem.Meal;

import java.util.ArrayList;
/**
 * RemoveMealToMenuController is a controller class for the Remove Meal GUI.
 * It handles the interaction between the GUI and the underlying data model.
 * @author Anka
 */
public class RemoveMealController {
    private RestaurantGUI restaurantGUI;
    @FXML
    private TableView<Meal> mealsTable;
    @FXML
    private TableColumn<Meal, String> nameColumn;
    @FXML
    private TableColumn<Meal, String> ingredientColumn;

    public void showError(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }
    public void showInformation(Stage stage, String title, String HeaderText, String contentText) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.initOwner(stage);
        alert.setTitle(title);
        alert.setHeaderText(HeaderText);
        alert.setContentText(contentText);
        alert.showAndWait();
    }

    public void setData(RestaurantGUI restaurantGUI) {
        this.restaurantGUI = restaurantGUI;
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        nameColumn.setStyle("-fx-alignment: CENTER;");
        ingredientColumn.setCellValueFactory(new PropertyValueFactory<>("ingredientsString"));
        ingredientColumn.setStyle("-fx-alignment: CENTER;");

        ArrayList<Meal> mealList = restaurantGUI.getRestaurantService().getMeals();
        ObservableList<Meal> meals = FXCollections.observableArrayList(mealList);
        mealsTable.setItems(meals);
    }

    @FXML
    public void confirmRemove() {
        Meal selectedMeal = mealsTable.getSelectionModel().getSelectedItem();
        try {
            if (selectedMeal != null) {
                restaurantGUI.getRestaurantService().getMeals().remove(selectedMeal);
                showInformation((Stage) mealsTable.getScene().getWindow(), "Success", "Meal Removed", "Meal " + selectedMeal.getName() + " has been removed successfully.");
                mealsTable.getItems().remove(selectedMeal);
            } else {
                showError((Stage) mealsTable.getScene().getWindow(), "Selection Error", "No Meal Selected", "Please select a meal to remove.");
            }
        } catch (Exception e) {
            showError((Stage) mealsTable.getScene().getWindow(), "Error", "Failed to remove meal", "Error: " + e.getMessage());
        }
    }
}
